package net.hoobo.lookzw.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.hoobo.lookzw.domain.VisitRecord;
import net.hoobo.lookzw.repository.impl.VisitRecordDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import static java.lang.Thread.dumpStack;
import static java.lang.Thread.sleep;


@Component
public class Look {
    private long id = 928534L;
    private String token = "Basic MTg5ODU3MTQ6M3d0ZUFFMHhkRnp2bGFFMkR" +
            "rc2lKd3I0bUtkZ3BVOFA4VTdPcks2anVjVkhiRzYzc1IwMnlua1FCOXVTYm9xOTAzb" +
            "VdBRzAxWDlxZkFkQW1EMzhPSmYwcGlWMWVKZ2FQRVZOR3FiN212RmIvTnIxQ0V1Vit3a" +
            "jFiMWxvamZkQUoyWnB6SVdaU2xCS1l1ZGpMaCttTGFxdkRjTENPU0Z0STIyTGJPeFpjQ1R" +
            "sWGp4VnFjUUUvcVJKcDFOQjFrSmJUVE0rUGNCaDIrYjJpMmtXU0Q1ZWVtRXR0ZHlhSTZydkh" +
            "UUGkrT2lNUGR6ZXZJRCswWFdVdjl0U3JLUEdnV2lnTXlkM3ZBU1Npd0lOUlUwa3p5OTlEYmg" +
            "vdy91aVkxREJET3RmbktvdFExR1UyYWppNkxtMkZSV2UrU1pjMUkxZXE1aVRWczRqRDFERy9l" +
            "U0s5ZktMa1FvUmtFSGxlelJHVnlsZkpoY0VSTDZxWVZ3TEVZRnV0UUc4RzdXcU1GVHlqSFdo" +
            "WmhZbms2dUhEL0JsaEYyMElNK1li";
    private String parm = "size=20&page=1";
    private String url = "https://106.75.64.129/users/18985714/visited";
    Map header = new HashMap(){{put("Authorization",token);}};
    @Autowired
    private VisitRecordDaoImpl visitRecordDao;
    private Thread thread;

    public Map getData(){
        for (int i=0;i<10;i++){
            String res = sendGet(url,header,parm);
            if(res!="") {
                JSONObject obj = JSON.parseObject(res);
                List data = (List)obj.get("data");
                for (Map row :(List<Map>)data) {
                    if ((long)(int)row.get("uid") == id) {
                        return row;
                    }
                }
                return new HashMap();
            }
            try {
                sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new HashMap();
    }

    public List<Map> getRecords(){
        List res= new ArrayList();
        for(VisitRecord record:visitRecordDao.findRecordById(id,null)){
            res.add(record.toMap());
        }
        return res;
    }

    public long getStatistic(Date date){
        long total = 0;
        for(VisitRecord record:visitRecordDao.findRecordById(id,date)){
            total +=record.getEndTime().getTime()-record.getStartTime().getTime();
        }
        return total/1000;
    }

    public boolean isLooking(){
        return thread.isAlive();
    }

    @PostConstruct
    private void looking(){
        thread = new Thread(){
            @Override
            public void run() {
                daemon();
            }
        };
        thread.setDaemon(true);
        thread.start();
        System.out.println("线程号："+thread.getId());
    }

    private void daemon(){
        long last_time = 0;
        boolean status = false;
        VisitRecord record= new VisitRecord();
        while(true) {
            Map row = getData();
            if (!row.isEmpty()){
                long uid = (long)(int)row.get("uid");
                long last_operate = (long)(int)row.get("last_operate");
                long delta = (new Date()).getTime()/1000-last_operate;
                if (!status && delta<300){
                    last_time = last_operate;
                    status = true;
                }else if(status && delta>300){
                    record.setUserId(uid);
                    record.setStartTime(new Date(last_time*1000));
                    if (last_time==last_operate) last_operate += 5;
                    record.setEndTime(new Date(last_operate*1000));
                    visitRecordDao.saveRecord(record);
                    status = false;
                }
                System.out.println(delta);
            }
            try {
                Random rand=new Random();
                int sleep_time = 80+rand.nextInt(40);
                sleep(sleep_time*1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class CustomizedHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String arg0, SSLSession arg1)
        {
            return true;
        }
    }

    public static String sendGet(String url, Map<String,String> header,String param) {

        String result = "";
        BufferedReader in = null;
        HttpsURLConnection connection = null;
        try {
            String urlNameString = url + "?" + param;
            connection = (HttpsURLConnection)new URL(urlNameString).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            connection.setHostnameVerifier(new CustomizedHostnameVerifier());
            for (String key :header.keySet()){
                connection.setRequestProperty(key,header.get(key));
            }
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (connection !=null){
                    connection.disconnect();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}
